<template>
  <div>
    <top-bar></top-bar>
    <left-bar :datas='data'></left-bar>
    <div class="adddrug system">
      <home-bar :currentPage='currentPage'></home-bar>
      <div class="adddrugs system-main">
        <div class="main-position">
          首页 > 商城管理 > {{currentPageName}}专场
        </div>
        <div class="main-height"></div>
        <div class="main-mains">
          <div class="main-top-nav">
            <ul>
              <li>
                <router-link to="/mallstoremgmt/pc" @click.native="addPath('/mallstoremgmt/pc','商城管理');">
                  店铺管理(pc)
                </router-link>
              </li>
              <li>
                <router-link to="/mallstoremgmt/sj" @click.native="addPath('/mallstoremgmt/sj','商城管理');">
                  店铺管理(sj)
                </router-link>
              </li>
              <li v-for="(item, index) in specialFieldList" :key="index" :class="{active:$route.params.id == item.id}">
                <router-link :to='"/mallproductmgmt/"+item.id' @click.native="addPath('/mallproductmgmt/'+item.id,'商城管理'); getPageList(item.id,item.name)">
                  {{item.name}}
                </router-link>
              </li>
            </ul>
          </div>
          <div class="drugListMain">
            <div class="headOperation">
              <el-button  size="medium" @click="addProduct(currentPageName)">添加{{currentPageName}}药品</el-button>
            </div>
            <div class="drugListTable">
              <table>
                <tr>
                  <td>
                    序号
                  </td>
                  <td>图片</td>
                  <td>药品分类</td>
                  <td>药品编码</td>
                  <td>药品名称</td>
                  <td>品牌</td>
                  <td>处方/非处方</td>
                  <td>经营范围</td>
                  <td>批发价</td>
                  <td>库存</td>
                  <td>信息费比例</td>
                  <td>药品状态</td>
                  <td>操作</td>
                </tr>
                <tr v-for="(item,index) in medicalList" :key="index">
                  <td>{{index + 1}}</td>
                  <td>
                    <img :src="item.image_url" alt="" class="trImg">
                  </td>
                  <td>{{item.category_name}}</td>
                  <td>{{item.coding}}</td>
                  <td>{{item.name}}</td>
                  <td>{{item.brand_name}}</td>
                  <td>{{item.is_recommend}}</td>
                  <td>{{item.scope_name}}</td>
                  <td>
                    <el-tooltip placement="top">
                      <div slot="content">{{item.pur_price}}</div>
                      <el-button>{{item.pur_price}}</el-button>
                    </el-tooltip>
                  </td>
                  <td>{{item.stock}}</td>
                  <td>{{item.info_fee_rate}}</td>
                  <td>{{item.status | filterStatus}}</td>
                  <td>
                    <el-tooltip placement="left">
                      <div slot="content">移除</div>
                      <el-button><i class="iconfont icon-shanchu" @click="removeDrug(2,item.id,item.name)"></i></el-button>
                    </el-tooltip>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </div>
      </div>
      <!-- 弹窗开始 -->
      <div class="system-menban" v-show="showSystemPopup"></div>
      <div class="systemPopup" v-show="showSystemPopup">
        <div class="topTitle">
          <span>{{systemPopupTitle}}</span>
          <i class="el-icon-close system-icon" @click="hideSystemPopup"></i>
        </div>
        <div class="addProductPopup" v-if="showAddProductPupup">
          <div class="seeCoding" v-show="showCodingInput">
            <span class="leftTitle">药品编码</span>
            <input type="text" placeholder="请输入药品编码或使用扫码枪扫码" v-model="codingValue" v-focus="focusCodingInput">
            <button @click="clickCodingResults">查询结果</button>
          </div>
          <div class="s-Tip">（最多可以添加25种{{currentPageName}}药品）</div>
          <div class="codingProductDetail clear" v-if="showCodingProductDetailPopup">
            <div class="basicInformation">
              <div class="codingTitle">药品信息</div>
              <ul>
                <li><span class="leftTitle">批次号</span>
                  <div class="rightContent">{{medical.lic_num}}</div>
                </li>
                <li><span class="leftTitle">药品名称</span>
                  <div class="rightContent">{{medical.name}}</div>
                </li>
                <li><span class="leftTitle">生产厂家</span>
                  <div class="rightContent">{{medical.manu_fac}}</div>
                </li>
                <li><span class="leftTitle">药品分类</span>
                  <div class="rightContent">{{medical.lic_num}}</div>
                </li>
                <li><span class="leftTitle">生产日期</span>
                  <div class="rightContent">{{medical.manu_date}}</div>
                </li>
                <li><span class="leftTitle">生产批号</span>
                  <div class="rightContent">{{medical.batch_num}}</div>
                </li>
                <li>
                  <span class="leftTitle">批发价</span>
                  <div class="rightContent">
                    <div v-for="(item,index) in medical.pur_price_list" :key="index">
                      <span>￥{{item.price}}（{{item.min_num}}-{{item.min_num}}件）</span>
                    </div>
                  </div>
                </li>
                <li><span class="leftTitle">当前库存</span>
                  <div class="rightContent">{{medical.stock}}件</div>
                </li>
                <li><span class="leftTitle">信息费比例</span>
                  <div class="rightContent">{{medical.info_fee_rate}}</div>
                </li>
                <li><span class="leftTitle">进货数量</span>
                  <div class="rightContent">{{medical.stock}}件</div>
                </li>
              </ul>
            </div>
            <div class="productImg">
              <div class="codingTitle">药品图片</div>
              <div class="productImgList">
                <img v-for="(item,index) in medical.image_list" :key="index" :src="item" alt="">
              </div>
            </div>
            <div class="addedProduct clear">
              <div class="codingTitle">已添加药品</div>
              <ul class="clear">
                <li v-for="(item,index) in addDurgNameList" :key="index">{{item.name}}<i class="delete" @click="deleteDurgName(index)">x</i></li>
              </ul>
            </div>
            <div class="system-messagebox1-btn clear">
              <div @click="changeDrugList(1)">确定</div>
              <div @click="hideSystemPopup">取消</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 弹窗结束 -->
    </div>
  </div>
</template>

<script>
  import topBar from "../../public/top";
  import leftBar from "../../public/left";
  import homeBar from "../../public/homebar";
  export default {
    components: {
      leftBar,
      topBar,
      homeBar
    },
    data() {
      return {
        data: "mallMgmt",
        currentPage: {
          path: "/mallproductmgmt/",
          name: "商城管理"
        },
        currentPageName: '',
        showSystemPopup: false, //弹窗总开关
        showAddProductPupup: false, //添加药品 （开关）
        showCodingInput: false, //编码输入框开关
        showCodingProductDetailPopup: false, //查询的药品详情
        focusCodingInput: false,
        systemPopupTitle: "", //标题
        codingValue: "", //编码
        input21: "",
        specialFieldList: [], //专场列表
        medicalList: [], //耀皮列表的药品
        medical: "", //查询结果的药品
        checkArr: [],
        checkCompleteArr: [],
        businessType: [],
        addDurgNameList: [],
      };
    },
    activated() {
      this.getSpecialFieldList();
      this.getPageList(this.$route.params.id,this.currentPageName);
    },
    methods: {
      //错误弹窗
      messageAlert(msg) {
        this.$message.error(msg);
      },
      //成功弹窗
      successfulAlert(msg) {
        this.$message({
          message: msg,
          type: 'success'
        });
      },
      //提示框
      infoAlert(msg) {
        this.$message(msg);
      },
      //获取专场列表(导航)
      getSpecialFieldList() {
        let _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/market/getSpecialFieldList/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token"),
            method: "get"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.specialFieldList = data.data.special_field_list;
              for(var i in _this.specialFieldList){
                if( _this.specialFieldList[i].id == _this.$route.params.id){
                  _this.currentPageName = _this.specialFieldList[i].name
                }
              }
              localStorage.setItem("nowTimes", new Date().getTime() / 1000);
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //获取当前专场的列表数据
      getPageList(id,currentPageName) {
        if(currentPageName == ""){
          this.currentPageName = this.currentPageName;
        }
        else{
          this.currentPageName = currentPageName;
        }
        let _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/market/getMedicalListWithSpecialField/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token") + "?special_field_id=" + id,
            method: "get"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.medicalList = data.data.medical_list;
              localStorage.setItem("nowTimes", new Date().getTime() / 1000);
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //点击查询结果
      clickCodingResults() {
        var _this = this;
        if (this.codingValue == "") {
          _this.messageAlert("请输入药品编码");
          return;
        }
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        // 请求开始
        _this
          .$http({
            url: this.urls +
              "/who/medical/getMedicalDetail/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token") + "?coding=" + this.codingValue + "&more=1",
            method: "get",
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.medical = data.data.medical;
              _this.addDurgNameList.push({
                name: data.data.medical.name,
                id: data.data.medical.id
              });
              if (_this.medical.info_fee_rate != undefined) {
                _this.medical.info_fee_rate = _this.medical.info_fee_rate * 100 + '%';
              }
              _this.showCodingProductDetailPopup = true;
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //删除单个药品名字
      deleteDurgName(index) {
        this.addDurgNameList.splice(index, 1);
      },
      //移除药品
      removeDrug(type, id, name) {
        this.$confirm("是否要移除：" + name, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.changeDrugList(type, id);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消移除'
          });
        });
      },
      //新增和移除药品  type: 1、添加药品；2、删除药品
      changeDrugList(type, id) {
        var _this = this;
        var special_field_id = "";
        if (type == 1) {
          //药品id(批量增加)
          var medical_ids = [];
          for (var i = 0; i < this.addDurgNameList.length; i++) {
            medical_ids.push(this.addDurgNameList[i].id);
          }
          medical_ids = medical_ids.join(",");
          //专场id
          special_field_id = parseInt(_this.$route.params.id);
        } else {
          var medical_ids = id;
        }
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        // 请求开始
        _this
          .$http({
            url: this.urls +
              "/who/market/operateSpecialField/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token"),
            method: "post",
            data: {
              type: type,
              special_field_id: special_field_id,
              medical_ids: medical_ids
            }
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      hideSystemPopup() {
        //关闭弹窗
        this.showSystemPopup = false;
        this.systemPopupTitle = "";
        this.showAddProductPupup = false;
        this.showCodingProductDetailPopup = false;
        this.codingValue = "";
      },
      addProduct(who) {
        this.focusCodingInput = true,
          this.showSystemPopup = true; //弹窗总开关
        this.showAddProductPupup = true; //添加药品 （开关）
        this.showCodingInput = true;
        this.systemPopupTitle = "添加" + who + "药品"; //标题
      },
      addPath(n1, n2) {
        //点击切换home-bar
        var obj = {};
        obj.n1 = n1;
        obj.n2 = n2;
        this.$store.commit("addPath", obj);
      }
    },
    filters: {
      filterStatus(value) {
        let types;
        if (value == 1) {
          types = '已上架'
        } else if (value == 2) {
          types = '已下架'
        } else if (value == 3) {
          types = '已删除'
        }
        return types;
      }
    },
    directives: {
      focus: {
        inserted: function(el, {
          value
        }) {
          if (value) {
            el.focus();
          }
        }
      }
    },
    watch: {
      'codingValue': function(val) {
        if (this.codingValue.length == 13) {
          this.clickCodingResults();
        }
      }
    },
  };
</script>

<style lang="less">
  @import "../css/mallList.less";
</style>
